package ua.khpi.si.kit49.diploma.util;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import ua.khpi.si.kit49.diploma.core.Weather;
import ua.khpi.si.kit49.diploma.service.WeatherServiceImpl;

/**
 * Class is in charge of making request to the yahoo weather service
 * 
 * @author netstalk3r
 * 
 */

public class WeatherUtilit implements Runnable {

	/**
	 * Logger
	 */
	private static final Logger log = Logger.getLogger(WeatherUtilit.class);

	private Integer id;
	private String request;
	private Weather weather;

	public WeatherUtilit(Integer id, String request, Weather weather) {
		super();
		this.id = id;
		this.request = request;
		this.weather = weather;
	}

	@Override
	public void run() {
		log.debug("Thread with id =" + this.id + " has started");
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(request);
		try {
			int statusCode = client.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				log.error("request fail");
				throw new RuntimeException(new HttpException(
						"company.error.http.request.error"));
			}
			InputStream is = method.getResponseBodyAsStream();
			new SAXUtilit(is, weather).parse();
		} catch (HttpException e) {
			log.error(e.getMessage());
			throw new RuntimeException(new HttpException(
					"company.error.weather.error"));
		} catch (IOException e) {
			log.error(e.getMessage());
			throw new RuntimeException(new IOException(
					"company.error.weather.IO.method.error"));
		} catch (ParserConfigurationException e) {
			log.error(e.getMessage());
			throw new RuntimeException(new ParserConfigurationException(
					"company.error.weather.parse.configuration.error"));
		} catch (SAXException e) {
			log.error(e.getMessage());
			throw new RuntimeException(new SAXException(
					"company.error.weather.sax.error"));
		}
		WeatherServiceImpl.reduceCount();
		log.debug("Thread with id =" + this.id + " has finished");
	}
}
